package jstart.exe;

import java.net.URL;
import java.util.logging.Logger;

/**
 * @author zwz
 * Created on 2020-09-09
 */
public class Main {

    private static final Logger logger = Logger.getLogger(Main.class.getSimpleName());

    public static void main(String[] args) {
        logger.info("It works!");
        launch(parseArgs(args));
    }

    private static String parseArgs(String[] args) {
        if (args == null || args.length == 0 || args[0].isEmpty()) {
            return null;
        }

        String firstArgv = args[0];
        if ("-l".equals(firstArgv) || "--launch".equals(firstArgv)) {
            return "launch";
        }
        if ("-u".equals(firstArgv) || "--update".equals(firstArgv)) {
            return "update";
        }
        return null;
    }

    private static void launch(String action) {
        logger.info("action=" + action);
        URL codeBase = Main.class.getProtectionDomain()
                                 .getCodeSource()
                                 .getLocation();
        ClassLoader currentClassLoader = Main.class.getClassLoader();
        Launcher launcher;
        if ("launch".equals(action)) {
            launcher = new StartLauncher(
                    new LaunchContext(codeBase, new AppClassLoader(currentClassLoader)));
        } else if ("update".equals(action)) {
            launcher = new UpdateLauncher(new LaunchContext(codeBase, currentClassLoader));
        } else {
            launcher =
                    new DefaultLauncher(new LaunchContext(codeBase, currentClassLoader));
        }

        try {
            launcher.launch();
        } catch (Exception e) {
            Kits.showMessageBox(null, true, "启动失败：\n"
                    + e.getClass()
                       .getCanonicalName()
                    + "\n"
                    + e.getMessage());
            System.exit(1);
        }
    }
}
